<template>
  <div class="components-container">
    <h1>麦克风实例</h1>
    <audio ref="audio" id="audio" controls autoplay></audio>
  </div>
</template>
<script>
import { defineComponent, onMounted, reactive, toRefs,ref } from 'vue'

export default defineComponent({
  setup() {
    const audio=ref(null)
    const constraints=window.constraints={
      audio:true,
      video:false,
    }
    const state=reactive({

    })
    onMounted(()=>{
      openMicPhone()
    })
    const openMicPhone=async ()=>{
      try{
        const stream=await navigator.mediaDevices.getUserMedia(constraints)
        console.log('success')
        handleSuccess(stream)
      }catch(e){
        console.log(e)
      }
    }
    const handleSuccess=(stream)=>{
      const audioTracks=stream.getAudioTracks();
      console.log("使用的设备是:"+audioTracks[0].label)
      window.stream=stream
      audio.value.srcObject=stream
    }
    return {
      ...toRefs(state),
      audio
    }
  },
})
</script>
<style scoped>
.components-container{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
</style>
